/**
 * @Injection.as
 * 
 * @author sodaChen mail:asframe@163.com
 * @version 1.0
 * <br>Copyright (C), 2012 ASFrame.com
 * <br>This program is protected by copyright laws.
 * <br>Program Name:ASFrame AStruts2
 * <br>Date:2012-4-30
 */
package com.asframe.astruts2.interfaces.impl
{
	import com.asframe.astruts2.Astruts2Const;
	import com.asframe.astruts2.context.IAStrutsContext;
	import com.asframe.astruts2.interfaces.IInjection;
	import com.asframe.collections.NullIterator;
	import com.asframe.pattern.observer.ISubjects;
	import com.asframe.pattern.observer.Subjects;
	import com.asframe.ref.Metadata;
	import com.asframe.ref.Method;
	import com.asframe.ref.Type;
	import com.asframe.ref.Variable;

	/**
	 *
	 * @author sodaChen
	 * @Date:2012-4-30
	 */
	public class Injection implements IInjection
	{
		/**
		 * @param obj 需要被注入操作的对象
		 * @param context 提供注入对象的容器
		 * 
		 */
		public function injection(obj:Object,type:Type,context:IAStrutsContext):void
		{
			var value:* = null;
			var metadata:Metadata = null;
			for each (var variable:Variable in type.variables) 
			{
				if(variable.isStatic)
				{
					continue;
				}
				//遍历,如果变量名在context里存在，则直接复制
				value = context.getBean(variable.name);
				//存在，并且类型相等
				if(value != null && (typeof(value) == variable.type))
				{
					invoke(obj,variable.name,value);
					continue;
				}
				//查看是否有相应的标签(自动注入标签Ref)
				metadata = variable.getMetadata(Astruts2Const.REF_METADATA);
				if(metadata != null)
				{
					var key:String = variable.name;
					if(metadata.firestArg != null)
					{
						key = metadata.firestArg.value;
					}
					value = context.getBean(variable.name);
				}
				if(value == null)
				{
					//TODO 为空，这里需要打印错误细腻
					continue;
				}
				invoke(obj,variable.name,value);
			}
		}
		private function invoke(obj:Object,key:String,value:*):void
		{
			try
			{
				obj[key] = value;
			}
			catch(error:Error)
			{
			}
		}
	}
}
